package org.allen.mst4j.service.impl;

import org.allen.mst4j.common.Constants;
import org.allen.mst4j.common.Logger;
import org.allen.mst4j.dao.BaseMapper;
import org.allen.mst4j.sysBean.PagerBean;
import org.allen.mst4j.sysBean.ResultBean;
import org.allen.mst4j.service.BaseService;
import org.sol.util.mybatis.MyBatisPojo;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


public abstract class BaseServiceImpl implements BaseService{

	protected void DEBUG(String msg) {
		if (Constants.DEBUG)
			Logger.SERVICE.debug(msg);
	}
	
	protected void LDEBUG(String msg,Object... objs) {
		if (Constants.DEBUG)
			Logger.SERVICE.ldebug(msg,objs);
	}
	
	@Override
	@Transactional(readOnly = true)
	public <T extends MyBatisPojo> PagerBean<T> select(T obj) {
		LDEBUG("查询数据 ",obj.tablename(),obj.toString());
		
		PagerBean<T> bean = new PagerBean<T>();
		bean.setRows(injectMapper().select(obj));

		return bean;
	}
	
	@Override
	@Transactional(readOnly = true)
	public <T extends MyBatisPojo> PagerBean<T> selectByPage(T obj) {
		LDEBUG("查询分页数据", obj.tablename(), obj.toString());
		
		PagerBean<T> bean = new PagerBean<T>();

		bean.setRows(injectMapper().selectByPage(obj));
		bean.setCount(injectMapper().count(obj));
		
		return bean;
	}
	
	@Override
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED,timeout = Constants.DB_TIMEOUT)
	public <T extends MyBatisPojo> ResultBean<T> insert(T obj) {
		DEBUG("插入数据 " + obj.toString());
		
		injectMapper().insert(obj);
		return ResultBean.RESULT_SUCCESS(obj);
	}
	
	@Override
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED,timeout = Constants.DB_TIMEOUT)
	public <T extends MyBatisPojo> ResultBean<T> update(T obj) {
		DEBUG("更新数据 " + obj.toString());
		
		injectMapper().update(obj);
		return ResultBean.RESULT_SUCCESS(obj);
	}
	
	@Override
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED,timeout = Constants.DB_TIMEOUT)
	public <T extends MyBatisPojo> ResultBean<T> delete(T obj) {
		DEBUG("删除数据 " + obj.toString());
		
		injectMapper().delete(obj);
		return ResultBean.RESULT_SUCCESS(obj);
	}

	/**
	 * 约定 - 继承类的通用Mapper名称为mapper
	 * @return
	 */
	protected BaseMapper injectMapper() {
		try {
			return (BaseMapper) getClass().getDeclaredField("mapper").get(this);
		} catch (Exception e) {
			Logger.SERVICE.debug("未找到约定映射器 mapper,类 -> " + this.getClass().getName());
			return null;
		}
	}

}
